﻿using MQTTnet;
using MQTTnet.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MQTTnet.Client;
using MQTTClient.Model;

namespace MQTTClient.Bll
{
    public class MQTTClientBll
    {
        private IMqttClient mqttClient = null; //客户端对象
        public string ClientId = "smyh1000";
        public string IP = "127.0.0.1";
        public int Port = 4500;
        public string UserName = "jiazhe";
        public string pwd = "123456";
        public IMqttClient MQTTClient
        {
            get { return mqttClient; }
            set { mqttClient = value; }
        }
        /// <summary>
        /// 发布数据
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="data">要发送的数据</param>
        public async void Publish_Data(string topic, string data)
        {
            await mqttClient.PublishAsync(new MqttApplicationMessage()
            {
                Topic = topic,                                                      // 主题
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,     // 消息等级 三个选项，最多一次，最少一次，刚好一次，从性能上来说，最多一次最高性能，刚好一次最损耗性能。一般工业现场的实时数据的推送都是最多一次即可               
                Payload = Encoding.UTF8.GetBytes(data),        // 数据
                Retain = false,                                                   // 消息是否要在服务器本地缓存，缓存之后新的客户端订阅消息的时候，会立即推送一次旧数据。
            });
        }
        
        /// <summary>
        /// 订阅的方法
        /// </summary>
        /// <param name="topic">订阅的主题</param>
        public void Subscribe_Topic(string topic)
        {
            mqttClient.SubscribeAsync(new List<TopicFilter> {
                new TopicFilter(topic, MqttQualityOfServiceLevel.AtMostOnce)
            });
        }
        /// <summary>
        /// 订阅公共主题
        /// </summary>
        public void Subscribe_PublicTopic()
        {
            Subscribe_Topic(SubscribeModel.PublicTopic);
        }
        /// <summary>
        /// 发布公共主题的数据
        /// </summary>
        /// <param name="data"></param>
        public  void Publish_PublicData(string data)
        {
             Publish_Data(SubscribeModel.PublicTopic,data);
        }
    }
}
